package com.holly.unit.deform;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.holly.unit.core.constants.CommonConstant;
import com.holly.unit.deform.api.DeformExtLinkApi;
import com.holly.unit.deform.config.DeformConfig;
import com.holly.unit.deform.util.BaseUrlUtil;
import com.holly.unit.deform.util.DeformUtil;
import com.holly.unit.deform.util.QiniuUtil;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 类描述: 表单设计外部链接 操作类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/12 8:53
 */
public class DeformExtLinkOperator extends DeformEngineOperator implements DeformExtLinkApi<ModelAndView>{

    private DeformConfig config;

    public DeformExtLinkOperator(DeformConfig config) {
        super(config);
    }

    @Override
    public ModelAndView externalAddDesformData(String desformCode, String reuseId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_ADD;
        if (StrUtil.isNotBlank(reuseId)) {
            urlType = CommonConstant.DESIGN_FORM_URL_TYPE_REUSE;
        } else {
            reuseId = "add";
        }
        return this.doFormView(modelAndView, urlType, desformCode, reuseId, null, request);
    }

    @Override
    public ModelAndView externalEditDesformData(String desformCode, String dataId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_EDIT;
        return this.doFormView(modelAndView, urlType, desformCode, dataId, null, request);
    }

    @Override
    public ModelAndView doSuccess(String desformCode, String dataId, ModelAndView mv, HttpServletRequest request) {
        ModelAndView mv1 = new ModelAndView();
        mv1 = queryFormViewByCode(desformCode, dataId, null, mv1);
        Map<String, Object> model = mv1.getModel();
        // 获取数据
        JSONObject designFormData = JSON.parseObject(JSON.parseObject(JSON.toJSONString(model.get("designFormData"))).getString("desformDataJson"));
        // 获取设计json
        JSONObject designForm = JSON.parseObject(JSON.toJSONString(model.get("designForm")));
        String desformDesignJson = designForm.getString("desformDesignJson");
        JSONObject json = JSON.parseObject(desformDesignJson);
        JSONArray dataList = json.getJSONArray("list");
        // 获取所有的字段
        List<JSONObject> widgets = new ArrayList<>();
        // 忽略部分显示
        List<String> ignores = Arrays.asList("button", "buttons", "grid", "card", "tabs", "text", "sub-table-design", "divider");
        DeformUtil.recursiveAllWidget(dataList, (type, item, parent) -> {
            if (type==null || !ignores.contains(type.getType())) {
                JSONObject widget = new JSONObject();
                String key = item.getString("model");
                String value = designFormData.getString(key);
                // 不展示空数据
                if (StrUtil.isNotBlank(value)) {
                    widget.put("title", item.getString("name"));
                    widget.put("modal", key);
                    widget.put("value", value);
                    widgets.add(widget);
                }
            }
        });
        mv.addObject("widgets", JSON.toJSONString(widgets));
        mv.setViewName("desform/result/success");
        return mv;
    }

    /**
     * @param mv
     * @param urlType
     * @param desformCode
     * @param dataId       数据Id，修改时用到
     * @param onlineDataId
     * @param request
     * @return
     */
    public ModelAndView doFormView(ModelAndView mv, String urlType, String desformCode, String dataId, String onlineDataId, HttpServletRequest request) {
        try {
            mv = queryFormViewByCode(desformCode, dataId, onlineDataId, true, mv);
            // 公共属性
            mv.addObject("action", CommonConstant.DESIGN_FORM_URL_TYPE_REUSE.equals(urlType) ? CommonConstant.DESIGN_FORM_URL_TYPE_ADD : urlType);
            mv.addObject("themeColor", config.getDesformThemeColor());
            mv.addObject("baseURL", BaseUrlUtil.getBaseUrl(request));
            mv.addObject("qiniuConfig", QiniuUtil.getConfig().toJSONString());
            // 模拟登陆
//            mv.addObject("mockToken", DesformUtils.getMockToken());
            // 最后返回 model and view
            mv.setViewName("desform/formGenerateExternal");
            return mv;
        }catch (Exception e) {
            e.printStackTrace();
            mv.addObject("message", e.getMessage());
        }
        mv.setViewName("desform/error");
        return mv;
    }



}
